from datetime import datetime
from bson.objectid import ObjectId

from app.extensions import db


class Tool:
    def __init__(self, name, slug, category, description, icon=None, **kwargs):
        self.name = name
        self.slug = slug
        self.category = category
        self.description = description
        self.icon = icon
        self.created_at = kwargs.get('created_at', datetime.utcnow())
        self.updated_at = kwargs.get('updated_at', datetime.utcnow())
        self.usage_count = kwargs.get('usage_count', 0)
        self.is_featured = kwargs.get('is_featured', False)
        self.config = kwargs.get('config', {})
        self._id = kwargs.get('_id', None)
    
    def get_id(self):
        return str(self._id)
    
    def to_dict(self):
        return {
            'name': self.name,
            'slug': self.slug,
            'category': self.category,
            'description': self.description,
            'icon': self.icon,
            'created_at': self.created_at,
            'updated_at': self.updated_at,
            'usage_count': self.usage_count,
            'is_featured': self.is_featured,
            'config': self.config
        }
    
    @classmethod
    def find_by_id(cls, tool_id):
        tool_data = db.db.tools.find_one({'_id': ObjectId(tool_id)})
        if not tool_data:
            return None
        tool_data['_id'] = tool_data['_id']
        return cls(**tool_data)
    
    @classmethod
    def find_by_slug(cls, slug):
        tool_data = db.db.tools.find_one({'slug': slug})
        if not tool_data:
            return None
        return cls(**tool_data)
    
    @classmethod
    def find_by_category(cls, category, limit=None):
        query = {'category': category}
        tools_data = db.db.tools.find(query).sort('name')
        if limit:
            tools_data = tools_data.limit(limit)
        return [cls(**tool_data) for tool_data in tools_data]
    
    @classmethod
    def get_featured_tools(cls, limit=None):
        query = {'is_featured': True}
        tools_data = db.db.tools.find(query).sort('usage_count', -1)
        if limit:
            tools_data = tools_data.limit(limit)
        return [cls(**tool_data) for tool_data in tools_data]
    
    @classmethod
    def search(cls, query, limit=None):
        search_query = {'$text': {'$search': query}}
        tools_data = db.db.tools.find(search_query)
        if limit:
            tools_data = tools_data.limit(limit)
        return [cls(**tool_data) for tool_data in tools_data]
    
    def save(self):
        tool_data = self.to_dict()
        if self._id:
            tool_data['updated_at'] = datetime.utcnow()
            db.db.tools.update_one({'_id': self._id}, {'$set': tool_data})
        else:
            result = db.db.tools.insert_one(tool_data)
            self._id = result.inserted_id
        return self
    
    def increment_usage(self):
        self.usage_count += 1
        db.db.tools.update_one(
            {'_id': self._id},
            {'$inc': {'usage_count': 1}}
        ) 